package view.bitmap
{
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.filters.DropShadowFilter;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.sampler.NewObjectSample;
	import flash.sampler.Sample;
	import flash.sampler.getSampleCount;
	import flash.sampler.getSamples;
	import flash.sampler.startSampling;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.clearInterval;
	import flash.utils.getQualifiedClassName;
	import flash.utils.getTimer;
	import flash.utils.setInterval;
	
	import spark.primitives.Rect;
	
	
	[Event(name="drawComplete",type="com.fminutes.vinciBitmap.BitmapMovieClipEvent")]
	[Event(name="drawFrameComp",type="com.fminutes.vinciBitmap.BitmapMovieClipEvent")]
	[Event(name="playToLast",type="com.fminutes.vinciBitmap.BitmapMovieClipEvent")]
	
	/**
	 * 位图化的MovieClip
	 * @author lipi
	 */
	public class BitmapMovieClip extends Sprite
	{
//		private static var _count:int;
		private var _playToListEvent:BitmapMovieClipEvent;
		
		public function BitmapMovieClip(mc:* = null)
		{
			super();
			
			if(mc == null) return;
			
//			_playToListEvent = new BitmapMovieClipEvent(BitmapMovieClipEvent.PLAY_TO_LAST)
			bitmap = new Bitmap();
			addChild(bitmap);
			
			mcArray = [];
			
			_timer = new Timer(1000/fps);
			_timer.addEventListener(TimerEvent.TIMER,timerEventHandler);
			_timer.start();
			
			if(mc is DisplayObject)
			{
				drawDisplayObject(mc);
				_mcSource = mc;
			}else{
				draw(mc);
			
				_mcClass = mc;
			}
			
			
			addEventListener(Event.ADDED_TO_STAGE,addToStageHandler);
			addEventListener(Event.REMOVED_FROM_STAGE,removeFromStage);
			
//			_count++;
//			trace("_count...................",_count);
		}
		
		private function addToStageHandler(e:Event):void
		{
			stage.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMover);
			_inStage = true;
//			_inStage = false;
		}
		private function removeFromStage(e:Event):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE,onMouseMover);
			_inStage = false;
		}
		
		
		private function onMouseMover(e:MouseEvent):void
		{
			if(transparentMouseEnabled == false)
			{
				if(this.hitTestPoint(e.stageX,e.stageY,true))
				{
					this.mouseEnabled = true;
					this.mouseChildren = true;
				}else{
					this.mouseEnabled = false;
					this.mouseChildren = false;
				}
			}
		}
		
		//这个对象是否在舞台中，如果不在舞台中应该不播动画
		private var _inStage:Boolean = false;
		
		private var _transparentMouseEnabled:Boolean = true;

		/**
		 * 透明区域的鼠标事件。如果对象所在容器已重写鼠标事件，请保持默认值 
		 */
		public function get transparentMouseEnabled():Boolean
		{
			return _transparentMouseEnabled;
		}

		/**
		 * @private
		 */
		public function set transparentMouseEnabled(value:Boolean):void
		{
			_transparentMouseEnabled = value;
			if(value)
			{
				this.mouseEnabled = true;
				this.mouseChildren = true;
			}else{
				this.mouseEnabled = false;
				this.mouseChildren = false;
			}
		}
		
		
		
		private var _mcClass:Class;
		private var _mcSource:DisplayObject;
		
		
		/**
		 * bitmap未准备好的 
		 */
		public static const UNCOMPLETE:int = 0;
		/**
		 * bitmap第一帧已完成 
		 */
		public static const COMPLETING:int = 1;
		/**
		 * bitmap全部已完成
		 */
		public static const COMPLETE:int = 2;
		
		
		private var bitmap:Bitmap;
		
		
		private function draw(mc:Class):void
		{
			BitmapManager.draw(mc,compFn,frameCompFn);
		}
		
		
		private function drawDisplayObject(mc:DisplayObject):void
		{
			BitmapProduced.draw(mc,compFn,frameCompFn);
		}
		
		private function compFn(data:Array,bTotalFrames:int):void
		{
			_totalFrames = bTotalFrames;
			mcArray = data;
			this.bitmapStatus = BitmapMovieClip.COMPLETE;
			_isStop = _outIsStop;
			go();
			dispatchEvent(new BitmapMovieClipEvent(BitmapMovieClipEvent.DRAW_COMPLETE));
		}
		private function frameCompFn(data:Array,bTotalFrames:int):void
		{
			_totalFrames = bTotalFrames;
			mcArray = data;
			if(this.bitmapStatus == BitmapMovieClip.UNCOMPLETE) this.bitmapStatus = BitmapMovieClip.COMPLETING;
			go();
			dispatchEvent(new BitmapMovieClipEvent(BitmapMovieClipEvent.DRAW_FRAME_COMP));
			
		}
		
		
		/**
		 * 位图的准备状态 
		 */
		public var bitmapStatus:int = 0;
		
		
		private var mcArray:Array;
		
		private var _timer:Timer;
		
		private var _currentFrame:uint = 0;
		
		
		private function timerEventHandler(e:TimerEvent):void
		{
			if(_inStage == false) return;
			if(_delayTime != 0)
			{
				if(getTimer() - _delayGetTime > _delayTime)
				{
					if(_delayStatus == "stop")
					{
						stop();
					}else{
						play();
					}
					_delayTime = 0;
				}
			}
			if(_isStop)
			{
				bitmap.smoothing = BitmapManager.smoothing;//消锯齿处理
				return;
			}
			_currentFrame ++; 
			
			if(_currentFrame >= mcArray.length)
			{
				_currentFrame = 0;
			}
			go();
			bitmap.smoothing = BitmapManager.smoothing;//消锯齿处理
		}
		
		private var $mcBitmapData:BitmapData;
		private function go():void
		{
			var $mcOffset:Point;
			if(mcArray == null || mcArray.length < 1)
			{
				_isStop = true;
			}else if(mcArray.length == 1){
				_isStop = true;
				$mcBitmapData = mcArray[0][0];
				$mcOffset = mcArray[0][1];
				bitmap.bitmapData = $mcBitmapData;
				bitmap.x = $mcOffset.x;
				bitmap.y = $mcOffset.y;
			}else{
				if(_currentFrame >= mcArray.length)
				{
					_currentFrame = mcArray.length - 1;
				}
				$mcBitmapData = mcArray[_currentFrame][0];
				$mcOffset = mcArray[_currentFrame][1];
				bitmap.bitmapData = $mcBitmapData;
				bitmap.x = $mcOffset.x;
				bitmap.y = $mcOffset.y;
			}
			
			if(_currentFrame +1 == totalFrames && totalFrames > 1)
			{
				dispatchEvent(new BitmapMovieClipEvent(BitmapMovieClipEvent.PLAY_TO_LAST));
			}
		}
		
		/**
		 * 获得当前帧的bitmapData
		 * @return 
		 */
		public function get bitmapData():BitmapData
		{
			return bitmap.bitmapData;
		}
		
		
		override public function hitTestPoint(x:Number, y:Number, shapeFlag:Boolean=false):Boolean
		{
			var $bitmapData:BitmapData = this.bitmapData;
			var p:Point;
			if(shapeFlag)
			{
				if($bitmapData != null)
				{
					p = bitmap.globalToLocal(new Point(x,y));
					var u:uint = $bitmapData.getPixel32(p.x,p.y);
					var rgb:uint = u & 0x00FFFFFF;
					u = u >> 24;
					if(u != 0x00 )
					{
						return true;
					}
				}
			}else{
				var rect:Rectangle = $bitmapData.rect;
				p = bitmap.globalToLocal(new Point(x,y));
				if(rect.containsPoint(p))
				{
					return true;
				}
			}
			return false;
		}
		
		
		private var _outIsStop:Boolean = false;//外部是否被设置为停止状态
		private var _isStop:Boolean = false;//当前是否为停止状态
		
		public function get currentFrame():int
		{
			return _currentFrame + 1;
		}
		
		private var _totalFrames:int = 0;
		public function get totalFrames():int
		{
			return _totalFrames;
//			if(mcArray == null) return 0;
//			return mcArray.length;
		}
		
		private var _fps:int = 24;
		/**
		 * 当前BitmapMovieClip的帧频
		 * @return 
		 */
		public function get fps():int
		{
			return _fps;
		}
		public function set fps(value:int):void
		{
			_fps = Math.max(value,1);
			_timer.delay = 1000/value;
		}
		
		public function stop():void
		{
			_isStop = true;
			_outIsStop = true;
			_delayTime = 0;
		}
		
		public function play():void
		{
			_isStop = false;
			_outIsStop = false;
			_delayTime = 0;
		}
		
		public function gotoAndPlay(frame:Object):void
		{
			if(frame is int)
			{
				var $frame:int = int(frame);
				if($frame > 0)
				{
					_currentFrame = $frame-1;
					go();
					play();
				}
			}
		}
		
		public function gotoAndStop(frame:Object):void
		{
			if(frame is int)
			{
				var $frame:int = int(frame);
				if($frame > 0)
				{
					_currentFrame = $frame-1;
					go();
					stop();
				}
			}
		}
		
		public function nextFrame():void
		{
			stop();
			_currentFrame ++; 
			go();
		}
		
		public function prevFrame():void
		{
			stop();
			_currentFrame --; 
			if(_currentFrame < 0)
			{
				_currentFrame = 0;
			}
			go();
		}
		
		private var _delayStatus:String = "play";
		private var _delayTime:int = 0;
		private var _delayGetTime:int = 0;
		
		/**
		 * 延迟一个时间点进行停止,如果当前不是play状态将被设置为play状态
		 * @param time 延迟的时间（毫秒）
		 */
		public function delayStop(time:int):void
		{
			_delayStatus = "stop";
			_delayTime = time;
			_isStop = false;
			_outIsStop = false;
			_delayGetTime = getTimer();
		}
		
		/**
		 * 延迟一个时间点进行播放,如果当前不是stop状态将被设置为stop状态
		 * @param time 延迟的时间（毫秒）
		 */
		public function delayPlay(time:int):void
		{
			_delayStatus = "play";
			_delayTime = time;
			_isStop = true;
			_outIsStop = true;
			_delayGetTime = getTimer();
		}
		
		
		
		
		public function destroy():void
		{
			if(_mcClass != null)
			{
				BitmapManager.destroy(_mcClass);
				_mcClass = null;
			}
			
			if(_mcSource != null)
			{
				BitmapProduced.getInstance().destroy(_mcSource);
				_mcSource = null;
			}
			
			if(_timer != null)
			{
				_timer.stop();
				_timer.removeEventListener(TimerEvent.TIMER,timerEventHandler);
				_timer = null;
			}
			
			removeEventListener(Event.ADDED_TO_STAGE,addToStageHandler);
			removeEventListener(Event.REMOVED_FROM_STAGE,removeFromStage);
		}
		
	}
}